package com.tutu.product.service.impl;


import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tutu.commons.clients.CategoryClient;
import com.tutu.commons.pojo.Category;
import com.tutu.commons.pojo.Product;
import com.tutu.commons.to.OrderToProduct;
import com.tutu.commons.utils.R;
import com.tutu.product.checks.GetProductByCategoryParam;
import com.tutu.product.mapper.ProductMapper;
import com.tutu.product.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Program: b2c-cloud-store
 * @Description:
 * @Author: JK.TuTu
 * @ @Version: 1.0
 * @Create: 2022-12-15 10:47
 **/
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private CategoryClient categoryClient;

    /**
     * 根据商品类别(单个或多个)名称 获取该类别下的所有商品信息
     *
     * @param categoryName 商品类别名称集合
     * @return 返回结果实体对象
     */
    @Override
    public R getProductInfo(List<String> categoryName) {
        //调用类别服务获取类别信息  获取类别id的集合
        List<Object> categoryIds = categoryName.stream().map((item) -> {
            R result = categoryClient.getCategoryByName(item);
            if (R.FAIL_CODE.equals(result.getCode())) {
                return R.fail("系统下没有该商品类别!");
            }
            //openfeign调用过程中会将result.getData的category自动转换成LinkedHashMap
            LinkedHashMap<String, Object> map = (LinkedHashMap<String, Object>) result.getData();
            return map.get("categoryId");
        }).collect(Collectors.toList());
        List<Product> products = productMapper.getProductByCategoryIds(categoryIds);
        return R.ok(products);
    }


    /**
     * 通过商品Id获取商品信息
     *
     * @param productId 商品Id
     * @return 返回结果实体对象
     */
    @Override
    public Product getProductInfoById(Integer productId) {
        return productMapper.selectById(productId);
    }

    /**
     * 根据商品分类ID获取商品的数据
     *
     * @param productParam 校验参数实体类
     * @return 返回结果实体类
     */
    @Override
    public R getProductsByCategoryId(GetProductByCategoryParam productParam) {
        LambdaQueryWrapper<Product> queryWrapper = new LambdaQueryWrapper<>();
        Object[] categoryIds = productParam.getCategoryId().toArray();
        queryWrapper.in(CollUtil.isNotEmpty(productParam.getCategoryId()), Product::getCategoryId, categoryIds);
        Page<Product> page = new Page<>(productParam.getCurrentPage(), productParam.getPageSize());
        Page<Product> productPage = this.page(page, queryWrapper);
        //获取总记录数
        long total = productPage.getTotal();
        return R.ok(null, productPage.getRecords(), total);
    }


    /**
     * 获取所有商品分类
     *
     * @return 商品分类集合
     */
    @Override
    public R getAllCategories() {
        R result = categoryClient.getAll();
        if (R.FAIL_CODE.equals(result.getCode())) {
            return R.fail(result.getMsg());
        }
        List<Category> categories = (List<Category>) result.getData();
        return R.ok(categories);
    }

    /**
     * 支持模糊查询商品信息
     *
     * @param param 查询商品实体检验
     * @return 返回结果实体类
     */
    @Override
    public R searchProduct(GetProductByCategoryParam param) {
        LambdaQueryWrapper<Product> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(Product::getProductName, param.getSearch());
        Page<Product> page = new Page<>(param.getCurrentPage(), param.getPageSize());
        Page<Product> productPage = this.page(page, queryWrapper);
        long total = productPage.getTotal();
        return R.ok(null, productPage.getRecords(), total);
    }

    /**
     * 修改商品信息
     *
     * @param orderToProducts 订单服务发送到商品服务的实体类
     */
    @Override
    public void updateProduct(List<OrderToProduct> orderToProducts) {
        for (OrderToProduct orderToProduct : orderToProducts) {
            LambdaQueryWrapper<Product> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Product::getProductId, orderToProduct.getProductId());
            Product product = productMapper.selectOne(queryWrapper);
            product.setProductNum(product.getProductNum() - orderToProduct.getNum());//减少库存
            product.setProductSales(product.getProductSales() + orderToProduct.getNum());//增加销量
            productMapper.updateById(product); //进行更新product表
        }
    }
}
